<?php


namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

use App\Model\Users;
use App\Model\Company;
use App\Model\Checkcategory;
use App\Model\MaterialList;
use App\Model\WarehouseMaterials;
use App\Model\Repairrecords;
use App\Model\Checkrecords;
use App\Model\Goods;
use App\Model\Maintainrecords;
use App\Model\Stock;
use PhpOffice\PhpWord\TemplateProcessor;
use App\Services\Export\WordChoose;
use PhpOffice\PhpWord\Element\Table;
use PhpOffice\PhpWord\SimpleType\TblWidth;
use Storage;
use App\Model\WarehouseOutbound;


class MaintenanceController extends Controller
{

    // 根据当前登录人查询下属企业和街道、社区的物资列表（users表的community字段）
    // 查询物资表的company_id  （需要整理接口文档）
    /**
     * 获取物资分类列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_goods_list(Request $request){
        // 查询物资表的信息
        $company_ids = $this->get_company_ids();
        $where = [];
        
        // 物资信息根据单位分组，无需分页查询
        // 物资分类的id
        // if($request['goods_id']){

        //     $where[] = ['goods_id','=',$request['goods_id']];
        // }
        // 所属单位的id
        if($request['checkcategory_id']){
            $where[] = ['checkcategory_id','=',$request['checkcategory_id']];
        }
        // 具体单位的id
        if($request['company_id']){
            $where[] = ['company_id','=',$request['company_id']];
        }
        // 物资分类和物资名称的模糊查询
        if($request['name']){
            // 名称模糊查询
           $material_ids = MaterialList::where('name','like','%'.$request['name'].'%')->pluck('id')->toArray();
           $where[] = ['material_id','in',$material_ids];
            // 物资类型模糊查询
            $goods_ids = Goods::where('name','like','%'.$request['name'].'%')->pluck('id')->toArray();
            $where[] = ['goods_id','in',$goods_ids];
        }

        if($company_ids){
            if($where){
                $list = Stock::with([
                    'goods:id,name',
                    'materialList:id,name',
                    'company:id,comName,leader,leaderPhone',
                    'checkcategory:id,name',
                ])->whereIn('company_id',$company_ids)->where($where)->groupBy('company_id')->get()->toArray();
            }else{
                $list = Stock::with([
                    'goods:id,name',
                    'materialList:id,name',
                    'company:id,comName,leader,leaderPhone',
                    'checkcategory:id,name',
                ])->whereIn('company_id',$company_ids)->groupBy('company_id')->get()->toArray();
            }
        }else{
            if($where){
                $list = Stock::with([
                    'goods:id,name',
                    'materialList:id,name',
                    'company:id,comName,leader,leaderPhone',
                    'checkcategory:id,name',
                ])->where($where)->groupBy('company_id')->get()->toArray();
            }else{
                $list = Stock::with([
                    'goods:id,name',
                    'materialList:id,name',
                    'company:id,comName,leader,leaderPhone',
                    'checkcategory:id,name',
                ])->groupBy('company_id')->get()->toArray();
            }
        }
        
        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'count' => count($list),
            'data'  => $list
        ];
        return response()->json($data);
        

    }


    // 查询相关单位列表 (不需要整理接口文档)
    public function get_company_ids(){

        if(Auth::user()->type ==1){
            $company_id = Company::pluck('id')->toArray();
        }else{
            $user_community = Auth::user()->community;
            $company_id = Company::where('community', $user_community)->pluck('id')->toArray();
        }

        return $company_id;
        
    }

    // 查询企业分类列表 (需要整理接口文档)
    public function get_category_list(){

        $list = Checkcategory::get()->toArray();
        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'count' => count($list),
            'data'  => $list
        ];
        return response()->json($data);
    }

    // 查询企业列表 （需要整理接口文档）

    public function get_company_list(Request $request){
        $company_ids = $this->get_company_ids();
        
        $where = [];
        if($request['category']){
            $where[] = ['category','=',$request['category']];
            $list = Company::select(['id','comName','leader','address'])->whereIn('id',$company_ids)->where($where)->get()->toArray();
        }else{
            $list = Company::whereIn('id',$company_ids)->get()->toArray();
        }

        // dump($list);exit;
        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'count' => count($list),
            'data'  => $list
        ];
        return response()->json($data);
    }



    public function get_number($type){

        switch($type){
            case 'PD':
                return 'PD' . time() . rand(1111,9999);
            break;
            case 'WX':
                return 'WX' . time() . rand(1111,9999);
            break;
            case 'BY':
                return 'BY' . time() . rand(1111,9999);
            break;
            default:
                return '';

        }
           
    }


    // 获取物资分类列表

    public function category(){
        // goods表的分类表
        $list = Goods::select(['id','name'])->get()->toArray();
        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'count' => count($list),
            'data'  => $list
        ];
        return response()->json($data);


    }



    // 查询盘点人/维修人/保养人

    public function check_user(Request $request){
        // 根据企业的id查询对应人员
        $company_id = $request['company_id'];

        // companyId
        $list = Users::select(['id','name'])->where('companyId', $company_id)->get()->toArray();
        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'count' => count($list),
            'data'  => $list
        ];
        return response()->json($data);

    }



    /**
     * 盘点
     */
    // 盘点记录 单位类型，单位id，开始和结束时间
    public function check_records(Request $request){
        $where = [];
        $where[] = ['is_delete','=',0]; 

        // api模块搜索关键字  模糊查询物资分类和物资名称
        if($request['name']){
            // 查询物资分类
            $goods_id = Goods::where('name','like','%'.$request['name'].'%')->pluck('id');
            if($goods_id){
                $where[] = ['goods_id','in',$goods_id];
            }
        
            // 查询物资名称
            $material_id = MaterialList::where('name','like','%'.$request['name'].'%')->pluck('id');
            if($material_id){
                $where[] = ['material_id','in',$material_id];
            }
        }
        $query = Checkrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where($where)->orderBy('id','desc')->orderBy('check_number','asc');
        

		$res=$query->paginate($request->get('limit',10))->toArray();
        foreach($res['data'] as &$v){
            $v['warehouse_materials']['number'] = $v['warehouse_number'];
            $v['warehouse_materials']['seat'] = $v['company']['address'];
             // 入库 盘点大于库存
             if($v['check_num'] > $v['warehouse_materials']['number'] ){
                $v['number'] = $v['check_num'] - $v['warehouse_materials']['number'];
                // 查询是否有入库记录
                $out = WarehouseMaterials::where('odd_numbers',$v['check_number'])->get();
                if(!empty($out)){
                    $v['warehousing'] = 1;
                }else{
                    $v['warehousing'] = 0;
                }
            }

            // dump($type);exit;
            // 出库是库存大于盘点
            // 查询库存记录表 库存数量大于盘点数量时是出库的信息
            if($v['warehouse_materials']['number'] > $v['check_num']){
                $v['number'] = $v['warehouse_materials']['number'] - $v['check_num'];
                // 查询是否有出库记录
                $out = WarehouseOutbound::where('odd_numbers',$v['check_number'])->get();
                if(!empty($out)){
                    $v['outbound'] = 1;
                }else{
                    $v['outbound'] = 0;
                }

            }
        }

        $data = [
			'code' => 200,
			'msg'   => '请求成功',
			'count' => $res['total'],
			'data'  => $res['data']
		];
		return response()->json($data);

    }

    
    // ***************  ***************
    // 盘点数据录入
    public function check_records_edit(Request $request){

        // warehouse_materials_id 物资表的id
        // check_num 盘点数量
        // check_remark 盘点备注

        // 盘点单号 
        // 遍历数据循环插入盘点记录表中 单个参数接收一个多维数组
        $check_data = json_decode($request->get('check_data'),true);
        $signature = $request->get('signature');
        $user_id = Auth::user()->id;
        
        $number = !empty($check_data[0]['id']) ? Checkrecords::where('id',$check_data[0]['id'])->value('check_number') : $this->get_number('PD');
        // dump($number);exit;
        $file_data = [];
        $time = date('Y-m-d H:i:s',time());
        if(!empty($check_data)){
            foreach($check_data as $v){
                if(isset($v['id']) && !empty($v['id'])){
 
                    // 编辑
                    $check = Checkrecords::find($v['id']);
                    $check->check_num = $v['check_num'];
                    $check->check_remark = isset($v['check_remark'])?$v['check_remark']:'';
                    $check->user_id = $user_id;//Auth::guard('admin')->user()->id
                    $check->created_at = $time();
                    $check->signature = $signature;
                    $file_data[] = $check;
                    $check->save();

                }else{
                    
                    // 查询物资表的数据
                    $data = $this->get_materials($v['warehouse_materials_id']);
                    // dump($data);exit;
                    if($data){
                        $data = $data->toArray();
                        $data['signature'] = $signature;
                        $data['warehouse_materials_id'] = $v['warehouse_materials_id'];
                        $data['check_num'] = $v['check_num'];
                        $data['check_remark'] = isset($v['check_remark'])?$v['check_remark']:'';
                        $data['check_number'] = $number;
                        $data['created_at'] = $time;
                        $data['user_id'] = $user_id;
                        $data['warehouse_number'] = $data['warehouse'];
                        unset($data['warehouse']);
                        // dump($data);exit;
                        $file_data[] = $data;
                        // $check = new Checkrecords();
                        $res = Checkrecords::insertGetId($data);
                    }else{
                        break;
                    }

                }
                
                
            }
            // 生成文档的方法调用
            $file = $this->check_file($file_data,$number);
            if($file){
                // 更新本次出库单号对应的相关数据的信息
                Checkrecords::where('check_number',$number)->update(['file'=>$file]);
            }
            $data = [
                'code' => 200,
                'msg'   => '请求成功',
                'count' => 0,
                'data'  => []
            ];
        }else{
            $data = [
                'code' => 500,
                'msg'   => '请求数据不可为空',
                'count' => 0,
                'data'  => []
            ];
        }
        
		return response()->json($data);


    }

    // 编辑的时候数据的查询
    public function check_edit_data(Request $request){
        $check_number = $request->get('check_number');
        // 根据盘点的编号查询数据
        $res = Checkrecords::with(
            [
                'goods:id,name',
                'materia:id,name',
                'company:id,comName,address',
                'users:id,name,phone',
                'warehouse_materials:id,warehouse as number,unit,norms'
            ]
            )->where('check_number',$check_number)->get();

        // $check_data = $this->processing_data($res);

        $data = [
			'code' => 200,
			'msg'   => '请求成功',
			'count' => count($res),
			'data'  => $res
		];
		return response()->json($data);
    }


    public function check_delete(Request $request){
        if(!empty($request['id'])){
			
			$res = Checkrecords::where('id',$request['id'])->update(['is_delete'=>1]);
            if($res){
                $data = [
                    'code' => 200,
                    'msg'   => '请求成功',
                    'count' => 0,
                    'data'  => array()
                ];
            }else{
                $data = [
                    'code' => 500,
                    'msg'   => '请求失败',
                    'count' => 0,
                    'data'  => array()
                ];
            }
			return response()->json($data);
		}


        if(empty($request['check_number'])){
			$data = [
				'code' => 500,
				'msg'   => '单号不可为空',
				'count' => 0,
				'data'  => array()
			];
			
			return response()->json($data);
		}
		// $exam=Checkrecords::findorfail($request['id']);
		// $exam->is_delete = 1;
		// $exam->save();
        $res = Checkrecords::where('check_number',$request['check_number'])->update(['is_delete'=>1]);
        if($res){
            $data = [
                'code' => 200,
                'msg'   => '请求成功',
                'count' => 0,
                'data'  => array()
            ];
        }else{
            $data = [
                'code' => 500,
                'msg'   => '请求失败',
                'count' => 0,
                'data'  => array()
            ];
        }
		
		
		return response()->json($data);
    }


    public function get_materials($id){
        // $data = WarehouseMaterials::where('id',$id)->select(['goods_id','material_id','checkcategory_id','company_id','number','norms','remarks','seat'])->first();
        $data = Stock::where('id',$id)->select(['goods_id','material_id','checkcategory_id','company_id','warehouse'])->first();
        if($data){
            return $data;

        }else{
            return array();
        }

    }
    // 



     
    /**
     * 维修
     */

    //  维修记录

    public function repair_records(Request $request){
        $where = [];
        $where[] = ['is_delete','=',0]; 
        // // 所属单位的id
        // if(!empty($request['checkcategory_id'])){
        //     $where[] = ['checkcategory_id','=',$request['checkcategory_id']];
        // }
        // // 具体单位的id
        // if(!empty($request['company_id'])){
        //     $where[] = ['company_id','=',$request['company_id']];
        // }

        // // 开始和结束时间
        // $start_time = strtotime($request['start_time']);
        // $end_time = strtotime($request['end_time']);
        // if(!empty($start_time) && !empty($end_time)){
        //     if($end_time < $start_time){
        //         $data = [
        //             'code' => 500,
        //             'msg'   => '结束时间必须大于开始时间',
        //             'count' => '',
        //             'data'  => ''
        //         ];
        //         return response()->json($data);
        //     }else{
    
        //         $where[] = ['created_at','between',[$start_time,$end_time]];
        //     }
        // }

        // api模块搜索关键字  模糊查询物资分类和物资名称
        if($request['name']){
            // 查询物资分类
            $goods_id = Goods::where('name','like','%'.$request['name'].'%')->pluck('id');
            if($goods_id){
                $where[] = ['goods_id','in',$goods_id];
            }
        
            // 查询物资名称
            $material_id = MaterialList::where('name','like','%'.$request['name'].'%')->pluck('id');
            if($material_id){
                $where[] = ['material_id','in',$material_id];
            }
        }
       
        $query = Repairrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where($where)->orderBy('id','desc')->orderBy('repair_number','asc');
        
        

		$res=$query->paginate($request->get('limit',10))->toArray();

        $data = [
			'code' => 200,
			'msg'   => '请求成功',
			'count' => $res['total'],
			'data'  => $res['data']
		];
		return response()->json($data);

    }

    // ***************  ***************
    
    // 维修数据录入
    public function repair_records_edit(Request $request){

        // warehouse_materials_id 物资表的id
        // repair_num 盘点数量
        // repair_remark 盘点备注

        // 遍历数据循环插入盘点记录表中 单个参数接收一个多维数组
        // $check_data = $request->get('check_data');
        $check_data = json_decode($request->get('check_data'),true);
        $signature = $request->get('signature');
        $user_id = Auth::user()->id;
        $number = isset($check_data[0]['id']) ? Repairrecords::where('id',$check_data[0]['id'])->value('repair_number') : $this->get_number('WX');
        $time = date('Y-m-d H:i:s',time());
        $file_data = [];
        if(!empty($check_data)){
            foreach($check_data as $v){
                if(isset($v['id']) && !empty($v['id'])){
                    // 编辑
                    $repair = Repairrecords::find($v['id']);
                    $repair->repair_num = $v['repair_num'];
                    $repair->repair_remark = isset($v['repair_remark'])?$v['repair_remark']:'';
                    $repair->created_at = $time;
                    $repair->signature = $signature;
                    $repair->user_id = $user_id;
                    $file_data[] = $repair;
                    $repair->save();

                }else{
                    // 查询物资表的数据
                    $data = $this->get_materials($v['warehouse_materials_id']);
                    $data = $data->toArray();
                    if($data){
                        $data['warehouse_materials_id'] = $v['warehouse_materials_id'];
                        $data['repair_num'] = $v['repair_num'];
                        $data['repair_remark'] = isset($v['repair_remark'])?$v['repair_remark']:'';
                        $data['user_id'] = $user_id;
                        $data['created_at'] = $time;
                        $data['repair_number'] = $number;
                        $data['signature'] = $signature;
                        unset($data['warehouse']);
                        $file_data[] = $data;
                        // $repair = new Repairrecords();
                        $res = Repairrecords::insertGetId($data);
                    }else{
                        break;
                    }

                }
                
                
            }

            // 生成文档的方法调用
            $file = $this->repair_file($file_data,$number);
            if($file){
                // 更新本次出库单号对应的相关数据的信息
                Checkrecords::where('check_number',$number)->update(['file'=>$file]);
            }
            $data = [
                'code' => 200,
                'msg'   => '请求成功',
                'count' => 0,
                'data'  => []
            ];
        }else{
            $data = [
                'code' => 500,
                'msg'   => '请求数据不可为空',
                'count' => 0,
                'data'  => []
            ];
        }
        
		return response()->json($data);

    }
    // 编辑的时候数据的查询
    public function repair_edit_data(Request $request){
        $check_number = $request->get('repair_number');
        // 根据盘点的编号查询数据
        $res = Repairrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where('repair_number',$check_number)->get();


        $data = [
			'code' => 200,
			'msg'   => '请求成功',
			'count' => count($res),
			'data'  => $res
		];
		return response()->json($data);
    }

    public function repair_delete(Request $request){

        if(!empty($request['id'])){
			
			$res = Repairrecords::where('id',$request['id'])->update(['is_delete'=>1]);
            if($res){
                $data = [
                    'code' => 200,
                    'msg'   => '请求成功',
                    'count' => 0,
                    'data'  => array()
                ];
            }else{
                $data = [
                    'code' => 500,
                    'msg'   => '请求失败',
                    'count' => 0,
                    'data'  => array()
                ];
            }
			return response()->json($data);
		}


        if(empty($request['repair_number'])){
			$data = [
				'code' => 500,
				'msg'   => '单号不可为空',
				'count' => 0,
				'data'  => array()
			];
			
			return response()->json($data);
		}
		// $exam=Checkrecords::findorfail($request['id']);
		// $exam->is_delete = 1;
		// $exam->save();
        $res = Repairrecords::where('repair_number',$request['repair_number'])->update(['is_delete'=>1]);
        if($res){
            $data = [
                'code' => 200,
                'msg'   => '请求成功',
                'count' => 0,
                'data'  => array()
            ];
        }else{
            $data = [
                'code' => 500,
                'msg'   => '请求失败',
                'count' => 0,
                'data'  => array()
            ];
        }
		
		
		return response()->json($data);
    }


    /**
     * 保养
     */

    //  保养记录

    public function maintain_records(Request $request){
        $where = [];
        $where[] = ['is_delete','=',0]; 
        // // 所属单位的id
        // if(!empty($request['checkcategory_id'])){
        //     $where[] = ['checkcategory_id','=',$request['checkcategory_id']];
        // }
        // // 具体单位的id
        // if(!empty($request['company_id'])){
        //     $where[] = ['company_id','=',$request['company_id']];
        // }

        // // 开始和结束时间
        // $start_time = strtotime($request['start_time']);
        // $end_time = strtotime($request['end_time']);
        // if(!empty($start_time) && !empty($end_time)){
        //     if($end_time < $start_time){
        //         $data = [
        //             'code' => 500,
        //             'msg'   => '结束时间必须大于开始时间',
        //             'count' => '',
        //             'data'  => ''
        //         ];
        //         return response()->json($data);
        //     }else{
    
        //         $where[] = ['created_at','between',[$start_time,$end_time]];
        //     }
        // }
        // api模块搜索关键字  模糊查询物资分类和物资名称
        if($request['name']){
            // 查询物资分类
            $goods_id = Goods::where('name','like','%'.$request['name'].'%')->pluck('id');
            if($goods_id){
                $where[] = ['goods_id','in',$goods_id];
            }
        
            // 查询物资名称
            $material_id = MaterialList::where('name','like','%'.$request['name'].'%')->pluck('id');
            if($material_id){
                $where[] = ['material_id','in',$material_id];
            }
        }


        $query = Maintainrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where($where)->orderBy('id','desc')->orderBy('maintain_number','asc');
        

		$res=$query->paginate($request->get('limit',10))->toArray();

        $data = [
			'code' => 200,
			'msg'   => '请求成功',
			'count' => $res['total'],
			'data'  => $res['data']
		];
		return response()->json($data);

    }

    // ***************  ***************

    // 保养数据录入
    public function maintain_records_edit(Request $request){

        // warehouse_materials_id 物资表的id
        // maintain_num 盘点数量
        // maintain_remark 盘点备注
        
        // 遍历数据循环插入盘点记录表中 单个参数接收一个多维数组
        // $check_data = $request->get('check_data');
        $check_data = json_decode($request->get('check_data'),true);
        $signature = $request->get('signature','');
        $user_id = Auth::user()->id;
        $number = isset($check_data[0]['id']) ? Maintainrecords::where('id',$check_data[0]['id'])->value('maintain_number') : $this->get_number('BY');
        $time = date('Y-m-d H:i:s',time());
        $file_data = [];
        if(!empty($check_data)){
            foreach($check_data as $v){
                if(isset($v['id']) && !empty($v['id'])){
                    // 编辑
                    $maintain = Maintainrecords::find($v['id']);
                    $maintain->maintain_num = $v['maintain_num'];
                    $maintain->maintain_remark = isset($v['maintain_remark'])?$v['maintain_remark']:'';
                    $maintain->created_at = $time;
                    $maintain->signature = $signature;
                    $maintain->user_id = $user_id;
                    $file_data[] = $maintain;
                    $maintain->save();

                }else{
                    // 查询物资表的数据
                    $data = $this->get_materials($v['warehouse_materials_id']);
                    
                    if($data){
                        $data = $data->toArray();
                        $data['warehouse_materials_id'] = $v['warehouse_materials_id'];
                        $data['maintain_num'] = $v['maintain_num'];
                        $data['maintain_remark'] = isset($v['maintain_remark'])?$v['maintain_remark']:'';
                        $data['maintain_number'] = $number;
                        $data['signature'] = $signature;
                        $data['created_at'] = $time;
                        $data['user_id'] = $user_id;
                        unset($data['warehouse']);
                        $file_data[] = $data;
                        
                        $res = Maintainrecords::insertGetId($data);
                    }else{
                        break;
                    }
                }
                
                
            }
            // 生成文档的方法调用
            $file = $this->maintain_file($file_data,$number);
            if($file){
                // 更新本次出库单号对应的相关数据的信息
                Checkrecords::where('check_number',$number)->update(['file'=>$file]);
            }
            $data = [
                'code' => 200,
                'msg'   => '请求成功',
                'count' => 0,
                'data'  => []
            ];
        }else{
            $data = [
                'code' => 500,
                'msg'   => '请求数据不可为空',
                'count' => 0,
                'data'  => []
            ];
        }
        
		return response()->json($data);


    }

    // 编辑的时候数据的查询
    public function maintain_edit_data(Request $request){
        $check_number = $request->get('maintain_number');
        // 根据盘点的编号查询数据
        $res = Maintainrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where('maintain_number',$check_number)->get();


        $data = [
			'code' => 200,
			'msg'   => '请求成功',
			'count' => count($res),
			'data'  => $res
		];
		return response()->json($data);
    }



    public function maintain_delete(Request $request){

        if(!empty($request['id'])){
			
			$res = Maintainrecords::where('id',$request['id'])->update(['is_delete'=>1]);
            if($res){
                $data = [
                    'code' => 200,
                    'msg'   => '请求成功',
                    'count' => 0,
                    'data'  => array()
                ];
            }else{
                $data = [
                    'code' => 500,
                    'msg'   => '请求失败',
                    'count' => 0,
                    'data'  => array()
                ];
            }
			return response()->json($data);
		}

        if(empty($request['maintain_number'])){
			$data = [
				'code' => 500,
				'msg'   => '单号不可为空',
				'count' => 0,
				'data'  => array()
			];
			
			return response()->json($data);
		}
		// $exam=Checkrecords::findorfail($request['id']);
		// $exam->is_delete = 1;
		// $exam->save();
        $res = Maintainrecords::where('maintain_number',$request['maintain_number'])->update(['is_delete'=>1]);
        if($res){
            $data = [
                'code' => 200,
                'msg'   => '请求成功',
                'count' => 0,
                'data'  => array()
            ];
        }else{
            $data = [
                'code' => 500,
                'msg'   => '请求失败',
                'count' => 0,
                'data'  => array()
            ];
        }
		
		
		return response()->json($data);
    }

     // 生成盘点单
     public function check_file($wdata,$number){
        
        if(empty($wdata) || empty($number)){
            return '';
        }
        $company_id = $wdata[0]['company_id'];
        // 查询对应的企业信息
        $company = Company::where(['id' => $company_id])->first();

        //  导出文件准备 新版更改为标准化评审不符合项及整改要求
        $processor =  new TemplateProcessor('./file_template/盘点单.docx');
        // dump( $processor);exit;
        $styleTable = array('borderSize' => 6, 'borderColor' => '999999'); //设置表格样式
        $cellRowSpan = array('vMerge' => 'restart', 'valign' => 'center'); // 设置可跨行，且文字在居中
        $cellRowContinue = array('vMerge' => 'continue'); //使行连接，且无边框线
        $cellColSpan = array('gridSpan' => 9, 'valign' => 'center'); //设置跨列
        $cellHCentered = array('align' => 'center'); //居中
        $cellHCentered1 = array('align' => 'left'); //
        $fontStyle = array('size'=>12,'bold'=>true,'valign'=>'center','align'=>'center','name'=>'宋体');
        $contentStyle = array('size'=>11,'valign'=>'left','align'=>'left','name'=>'宋体');
        $cellVCentered = array('valign' => 'center'); //居中


        $table = new Table(array('borderSize' => 6, 'borderColor' => 'black', 'width' => 8500, 'unit' => TblWidth::TWIP));

        /*添加table头部*/
        $table->addRow();  //添加一行

        $table->addCell(0, $cellRowSpan)->addText('类 别',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('序 号',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('物品名称',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('单 位',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('规 格',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('账面数量',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('盘点数量',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('备 注',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 

        $data['company_name'] = $company ? $company['comName'] : '';
        $data['number'] = $number;
        $data['table'] = array();
        $data['user_name'] = Auth::user()->name;//库管员,当前操作人
        $data['name'] = $company['leader'];//单位的负责人
        $data['date'] = date('Y年m月d日',time());

        foreach($wdata as $k=>$v) {
            
            
            $tmp_arr = array();

            // 查询其他的数据
            $goods_name = Goods::where('id',$v['goods_id'])->pluck('name')->first();

            $material = Stock::with([
                'goods:id,name',
                'materialList:id,name',
                'company:id,comName,leader,leaderPhone',
                'checkcategory:id,name',])->where('id',$v['warehouse_materials_id'])->first();
                

                // 新

                $tmp_arr['category'] = $goods_name;//类别
                $tmp_arr['number'] = $k + 1;//序号
                $tmp_arr['name'] = $material['materialList']['name'];//物品名称
                $tmp_arr['unit'] = $material['unit'];//单位
                $tmp_arr['guige'] = $material['norms'];//规格
                $tmp_arr['num'] = $v['warehouse_number'];//账面数量
                $tmp_arr['check_num'] = $v['check_num'];//盘点数量check_num
                $tmp_arr['remark'] = $v['check_remark'] ;//备注

                
                $data['table'][]=$tmp_arr;  //正常赋值用于word中的表格遍历

                $table->addRow();  //添加一行
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['category'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['number'],$fontStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['name'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['unit'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['guige'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['num'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['check_num'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['remark'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
            
            
            
        }
        // dump($data);exit;

        $processor->setComplexBlock('table', $table);
        foreach ($data as $key => $value) {
            if($key!='table') {
                $processor->setValue($key, $value);
            }  
        }

        $docName = $company['comName'].'物资盘点单' ;
        $created = date('Ymd',time());
        Storage::disk('public')->makeDirectory('word/'.$created);
        $word_url = './storage/word/'.$created.'/'.$docName.'.docx';
        $processor->saveAs($word_url);
        $wordUrl = ltrim($word_url,'.');

        return $wordUrl;


    }

    // 生成维修单

    public function repair_file($wdata,$number){
        if(empty($wdata) || empty($number)){
            return '';
        }
        $company_id = $wdata[0]['company_id'];
        // 查询对应的企业信息
        $company = Company::where(['id' => $company_id])->first();

        //  导出文件准备 新版更改为标准化评审不符合项及整改要求
        $processor =  new TemplateProcessor('./file_template/维修单.docx');
        // dump( $processor);exit;
        $styleTable = array('borderSize' => 6, 'borderColor' => '999999'); //设置表格样式
        $cellRowSpan = array('vMerge' => 'restart', 'valign' => 'center'); // 设置可跨行，且文字在居中
        $cellRowContinue = array('vMerge' => 'continue'); //使行连接，且无边框线
        $cellColSpan = array('gridSpan' => 9, 'valign' => 'center'); //设置跨列
        $cellHCentered = array('align' => 'left'); //居中
        $cellHCentered1 = array('align' => 'left'); //
        $fontStyle = array('size'=>12,'bold'=>true,'valign'=>'center','align'=>'center','name'=>'宋体');
        $contentStyle = array('size'=>12,'valign'=>'left','align'=>'left','name'=>'宋体');
        $cellVCentered = array('valign' => 'center'); //居中


        $table = new Table(array('borderSize' => 6, 'borderColor' => 'black', 'width' => 8500, 'unit' => TblWidth::TWIP));

        /*添加table头部*/
        $table->addRow();  //添加一行
        $table->addCell(0, $cellRowSpan)->addText('类 别',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('序 号',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('物品名称',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('单 位',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('规 格',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('账面数量',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('盘点数量',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('维修详情',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 


        $data['company_name'] = $company ? $company['comName'] : '';
        $data['number'] = $number;
        $data['table'] = array();
        $data['user_name'] = Auth::user()->name;//库管员,当前操作人
        $data['name'] = $company['leader'];//单位的负责人
        $data['date'] = date('Y年m月d日',time());

        foreach($wdata as $k=>$v) {
            
            
            $tmp_arr = array();

            // 查询其他的数据
            $goods_name = Goods::where('id',$v['goods_id'])->pluck('name')->first();
            $material = Stock::with([
            'goods:id,name',
            'materialList:id,name',
            'company:id,comName,leader,leaderPhone',
            'checkcategory:id,name',])->where('id',$v['warehouse_materials_id'])->first();
            // dump($goods_name);exit;

                // 新

                $tmp_arr['category'] = $goods_name;//类别
                $tmp_arr['number'] = $k + 1;//序号
                $tmp_arr['name'] = $material['materialList']['name'];//物品名称
                $tmp_arr['unit'] = $material['unit'];//单位
                $tmp_arr['guige'] = $material['norms'];//规格
                $tmp_arr['num'] = $material['warehouse'];//账面数量
                $tmp_arr['repair_num'] = $v['repair_num'];//盘点数量check_num
                $tmp_arr['remark'] = $v['repair_remark'] ;//备注

                
                $data['table'][]=$tmp_arr;  //正常赋值用于word中的表格遍历

                $table->addRow();  //添加一行
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['category'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['number'],$fontStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['name'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['unit'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['guige'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['num'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['repair_num'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['remark'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
            
            
            
        }
        // dump($data);exit;

        $processor->setComplexBlock('table', $table);
        foreach ($data as $key => $value) {
            if($key!='table') {
                $processor->setValue($key, $value);
            }  
        }

        $docName = $company['comName'].'物资维修单' ;
        $created = date('Ymd',time());
        Storage::disk('public')->makeDirectory('word/'.$created);
        $word_url = './storage/word/'.$created.'/'.$docName.'.docx';
        $processor->saveAs($word_url);
        $wordUrl = ltrim($word_url,'.');

        return $wordUrl;
    }


    // 生成保养单

    public function maintain_file($wdata,$number){
        if(empty($wdata) || empty($number)){
            return '';
        }
        $company_id = $wdata[0]['company_id'];
        // 查询对应的企业信息
        $company = Company::where(['id' => $company_id])->first();

        //  导出文件准备 新版更改为标准化评审不符合项及整改要求
        $processor =  new TemplateProcessor('./file_template/保养单.docx');
        // dump( $processor);exit;
        $styleTable = array('borderSize' => 6, 'borderColor' => '999999'); //设置表格样式
        $cellRowSpan = array('vMerge' => 'restart', 'valign' => 'center'); // 设置可跨行，且文字在居中
        $cellRowContinue = array('vMerge' => 'continue'); //使行连接，且无边框线
        $cellColSpan = array('gridSpan' => 9, 'valign' => 'center'); //设置跨列
        $cellHCentered = array('align' => 'left'); //居中
        $cellHCentered1 = array('align' => 'left'); //
        $fontStyle = array('size'=>12,'bold'=>true,'valign'=>'center','align'=>'center','name'=>'宋体');
        $contentStyle = array('size'=>12,'valign'=>'left','align'=>'left','name'=>'宋体');
        $cellVCentered = array('valign' => 'center'); //居中


        $table = new Table(array('borderSize' => 6, 'borderColor' => 'black', 'width' => 8500, 'unit' => TblWidth::TWIP));

        /*添加table头部*/
        $table->addRow();  //添加一行
        $table->addCell(0, $cellRowSpan)->addText('类 别',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('序 号',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('物品名称',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('单 位',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('规 格',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('账面数量',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('盘点数量',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 
        $table->addCell(0, $cellRowSpan)->addText('保养项目',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中 


        $data['company_name'] = $company ? $company['comName'] : '';
        $data['number'] = $number;
        $data['table'] = array();
        $data['user_name'] = Auth::user()->name;//库管员,当前操作人
        $data['name'] = $company['leader'];//单位的负责人
        $data['date'] = date('Y年m月d日',time());

        foreach($wdata as $k=>$v) {
            
            
            $tmp_arr = array();

            // 查询其他的数据
            $goods_name = Goods::where('id',$v['goods_id'])->pluck('name')->first();
            // $material = WarehouseMaterials::where('id',$v['warehouse_materials_id'])->first();
            $material = Stock::with([
                'goods:id,name',
                'materialList:id,name',
                'company:id,comName,leader,leaderPhone',
                'checkcategory:id,name',])->where('id',$v['warehouse_materials_id'])->first();
            // dump($goods_name);exit;

                // 新

                $tmp_arr['category'] = $goods_name;//类别
                $tmp_arr['number'] = $k + 1;//序号
                $tmp_arr['name'] = $material['materialList']['name'];//物品名称
                $tmp_arr['unit'] = $material['unit'];//单位
                $tmp_arr['guige'] = $material['norms'];//规格
                $tmp_arr['num'] = $material['warehouse'];//账面数量
                $tmp_arr['maintain_num'] = $v['maintain_num'];//盘点数量check_num
                $tmp_arr['remark'] = $v['maintain_remark'] ;//备注

                
                $data['table'][]=$tmp_arr;  //正常赋值用于word中的表格遍历

                $table->addRow();  //添加一行
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['category'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['number'],$fontStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['name'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['unit'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['guige'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['num'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['maintain_num'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
                $table->addCell(0, $cellRowSpan)->addText($tmp_arr['remark'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 
            
            
            
        }
        // dump($data);exit;

        $processor->setComplexBlock('table', $table);
        foreach ($data as $key => $value) {
            if($key!='table') {
                $processor->setValue($key, $value);
            }  
        }

        $docName = $company['comName'].'物资保养单' ;
        $created = date('Ymd',time());
        Storage::disk('public')->makeDirectory('word/'.$created);
        $word_url = './storage/word/'.$created.'/'.$docName.'.docx';
        $processor->saveAs($word_url);
        $wordUrl = ltrim($word_url,'.');

        return $wordUrl;
    }




    // 根据盘点单号查询盘点出入库的相关数据信息
    public function materials_data(Request $request){

        $number = $request['number'];
        $type = $request['type'];//1是出库2是入库
        
        if(!$number){
			$data = [
				'code' => 500,
				'msg'   => '盘点单号不可为空',
				'count' => 0,
				'data'  => array()
			];
			
			return response()->json($data);
		}
        // 查询单号所属的全部数据
        $check_data = Checkrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'checkcategory:id,name',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where('check_number',$number)
        ->select(['id','check_num','check_number','check_remark','goods_id','warehouse_materials_id','material_id','company_id','warehouse_number','checkcategory_id'])->get()->toArray();
       
        $list = [];
        foreach($check_data as $v){
            if($type==1){
                // 入库
                if($v['warehouse_number'] < $v['check_num']){
                    $v['check_num'] = $v['check_num'] - $v['warehouse_number'];
                    $list[] = $v;
                }
            }else{
                // dump($type);exit;
                // 查询库存记录表 库存数量大于盘点数量时是出库的信息
                if($v['warehouse_number'] > $v['check_num']){
                    $v['check_num'] = $v['warehouse_number'] - $v['check_num'];
                    $list[] = $v;
                }
            }

        }
        $data = [
            'code' => 200,
            'msg'   => '查询成功',
            'count' => count($list),
            'data'  => $list
        ];
        
        return response()->json($data);
    }


    public function check_detail(Request $request){

        $check_number = $request->get('check_number');//单号
        $wdata = Checkrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'checkcategory:id,name',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where('check_number',$check_number)
        ->select(['id','check_num','check_number','check_remark','goods_id','warehouse_materials_id','material_id','company_id','created_at','warehouse_number','checkcategory_id'])->get()->toArray();
        // dump($wdata[0]['created_at']);exit;
        $company_id = !empty($wdata[0])?$wdata[0]['company_id']:0;
        // 查询对应的企业信息
        $company = Company::where(['id' => $company_id])->first();
        

            foreach($wdata as &$v){
            $v['warehouse_materials']['number'] = $v['warehouse_number'];
            $v['warehouse_materials']['seat'] = $v['company']['address'];
             // 入库 盘点大于库存
             if($v['check_num'] > $v['warehouse_materials']['number'] ){
                $v['number'] = $v['check_num'] - $v['warehouse_materials']['number'];
                // 查询是否有入库记录
                $out = WarehouseMaterials::where('odd_numbers',$v['check_number'])->get();
                if(!empty($out) && count($out)>=1){
                    $v['warehousing'] = 1;
                    $v['outbound'] = 0;
                }else{
                    $v['warehousing'] = 0;
                    $v['outbound'] = 0;
                }
            }

            // dump($type);exit;
            // 出库是库存大于盘点
            // 查询库存记录表 库存数量大于盘点数量时是出库的信息
            if($v['warehouse_materials']['number'] > $v['check_num']){
                $v['number'] = $v['warehouse_materials']['number'] - $v['check_num'];
                // 查询是否有出库记录
                $out = WarehouseOutbound::where('odd_numbers',$v['check_number'])->get();
                if(!empty($out) && count($out)>=1){
                    $v['outbound'] = 1;
                    $v['warehousing'] = 0;
                }else{
                    $v['outbound'] = 0;
                    $v['warehousing'] = 0;
                }

            }
        }
            $data['check_records'] = $wdata;
            $data['company_name'] = $company ? $company['comName'] : '';
            $data['number'] = $check_number;
            $data['user_name'] = Auth::user()->name;//库管员,当前操作人
            $data['name'] = $company['leader'];//单位的负责人
            $data['date'] = !empty($wdata[0])?$wdata[0]['created_at']:'';

        $return_data = [
            'code' => 200,
            'msg'   => '查询成功',
            'count' => count($wdata),
            'data'  => $data
        ];
        
        return response()->json($return_data);
    }

    public function repair_detail(Request $request){

        $check_number = $request->get('repair_number');//单号
        $wdata = Repairrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where('repair_number',$check_number)
        ->select(['id','repair_num','repair_number','repair_remark','goods_id','warehouse_materials_id','material_id','company_id','created_at'])->get()->toArray();
        // dump($wdata[0]);exit;.

        $company_id = !empty($wdata[0])?$wdata[0]['company_id']:0;
        // 查询对应的企业信息
        $company = Company::where(['id' => $company_id])->first();
        $data['repair_records'] = $wdata;
        $data['company_name'] = $company ? $company['comName'] : '';
        $data['number'] = $check_number;
        $data['user_name'] = Auth::user()->name;//库管员,当前操作人
        $data['name'] = $company['leader'];//单位的负责人
        $data['date'] = !empty($wdata[0])?$wdata[0]['created_at']:'';

        $return_data = [
            'code' => 200,
            'msg'   => '查询成功',
            'count' => count($wdata),
            'data'  => $data
        ];
        
        return response()->json($return_data);
    }
    public function maintain_detail(Request $request){

        $check_number = $request->get('maintain_number');//单号
        $wdata = Maintainrecords::with([
            'goods:id,name',
            'materia:id,name',
            'company:id,comName,address',
            'users:id,name,phone',
            'warehouse_materials:id,warehouse as number,unit,norms'
        ])->where('maintain_number',$check_number)
        ->select(['id','maintain_num','maintain_number','maintain_remark','goods_id','warehouse_materials_id','material_id','company_id','created_at'])->get()->toArray();
        // dump($wdata[0]);exit;

        $company_id = !empty($wdata[0])?$wdata[0]['company_id']:0;
        // 查询对应的企业信息
        $company = Company::where(['id' => $company_id])->first();
        $data['maintain_records'] = $wdata;
        $data['company_name'] = $company ? $company['comName'] : '';
        $data['number'] = $check_number;
        $data['user_name'] = Auth::user()->name;//库管员,当前操作人
        $data['name'] = $company['leader'];//单位的负责人
        $data['date'] = !empty($wdata[0])?$wdata[0]['created_at']:'';

        $return_data = [
            'code' => 200,
            'msg'   => '查询成功',
            'count' => count($wdata),
            'data'  => $data
        ];
        
        return response()->json($return_data);
    }



}